package com.zy;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.MemoryId;
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;

/**
 * @program: AI_langchain4j
 * @description:
 * @author: zy
 * @create: 2025-06-30 17:16
 */
public class Test {
    //工具类
    static class MyTools {
        @Tool("求多个数的和")
        public int add(int...nums) {
            int total = 0;
            for (int num : nums) {
                total += num;
            }
            System.out.println("total = " + total);
            return total;
        }
        @Tool("求一个字符串的长度")
        public int length(String str) {
            System.out.println("length = " + str.length());
            return str.length();
        }

        @Tool("计算一个数的平方根")
        public double sqrt(double num) {
            System.out.println("sqrt = " + Math.sqrt(num));
            return Math.sqrt(num);
        }

        // 温度单位的枚举类
        public enum TemperatureUnit {
            CELSIUS, FAHRENHEIT, KELVIN
        }

        @JsonIgnoreProperties(ignoreUnknown = true)
        public static class WeatherResponse {
            @JsonProperty("results")
            public List<WeatherData> results;

            @JsonIgnoreProperties(ignoreUnknown = true)
            public static class WeatherData {
                @JsonProperty("location")
                @JsonIgnoreProperties(ignoreUnknown = true)
                public Location location;

                @JsonProperty("now")
                @JsonIgnoreProperties(ignoreUnknown = true)
                public Now now;

                @JsonIgnoreProperties(ignoreUnknown = true)
                public static class Location {
                    @JsonProperty("name")
                    public String name;
                    // 其他字段会被自动忽略
                }

                @JsonIgnoreProperties(ignoreUnknown = true)
                public static class Now {
                    @JsonProperty("text")
                    public String text;
                    @JsonProperty("temperature")
                    public String temperature;
                    @JsonProperty("code")  // 新增code字段
                    public String code;  // 虽然不使用但需要定义
                }
            }
        }

        @Tool("用户会询问某个城市的天气,他还会给你温度单位，请返回城市的天气情况")
        public String getWeather(
                @P("城市名称") String city,
                @P("温度单位") TemperatureUnit unit
        ) {
            try {
                String apiKey = "SlUbsQwIT-x7oPyEC";
                String url = String.format(
                        "https://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=zh-Hans&unit=c",
                        apiKey, URLEncoder.encode(city, "UTF-8")
                );

                HttpClient client = HttpClient.newHttpClient();
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(url))
                        .timeout(Duration.ofSeconds(10))
                        .build();

                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                String json = response.body();

                ObjectMapper mapper = new ObjectMapper();
                WeatherResponse weatherResponse = mapper.readValue(json, WeatherResponse.class);

                WeatherResponse.WeatherData.Now now = weatherResponse.results.get(0).now;
                return String.format("%s的天气：%s，气温 %s°C", city, now.text, now.temperature);
            } catch (Exception e) {
                e.printStackTrace();
                return "获取天气失败：" + e.getMessage();
            }
        }


//        @Tool("返回给定城市的天气")
//        public String getWeather(
//                @P("要返回天气信息的城市名称") String city,
//                @P("温度的单位") TempratureUnit unit
//        ) {
//            //TODO:访问一个开发API获取天气信息
//            Random r = new Random();
//            int tempC = 15+r.nextInt(15); //随机生成15到30之间的温度
//            String v = "°C";
//            double displayTemp = tempC;
//            if(unit==TempratureUnit.FAHRENHEIT) {
//                displayTemp = tempC*9/5+32;
//                v = "F";
//            }else if(unit==TempratureUnit.KELVIN) {
//                displayTemp = tempC+273.15;
//                v = "K";
//            }
//            String[] conditions = {"Sunny", "Cloudy", "Rainy", "Snowy"};
//            return String.format("The weather in %s is %s with a temperature of %.1f %s",
//                    city, conditions[r.nextInt(conditions.length)], displayTemp, v);
//        }
    }
    interface  Assistant {
        @SystemMessage("你是一个有用的助手，帮助用户解决各种生活中和学习上的问题")
        String chat(@MemoryId int memoryId, @UserMessage String userMessage);
    }

    //AIServiece+基于redis的chatMemory+tools+userid
    public static void main(String[] args) {
        PersistentChatMemoryStore store = new PersistentChatMemoryStore();
        //创建一个chatMemoryProvider对象，用于创建chatMemory对象
        ChatMemoryProvider chatMemoryProvider = memoryId -> MessageWindowChatMemory.builder()
                .id(memoryId)
                .maxMessages(1000)
                .chatMemoryStore(store)
                .build();

        String apiKey = System.getenv("OPEN_AI_KEY");
        OpenAiChatModel model = OpenAiChatModel.builder()
                .apiKey(apiKey)
                .modelName("deepseek-chat")
                .baseUrl("https://api.deepseek.com")
                //.logRequests(true)
                //.logResponses(true)
                .timeout(Duration.ofMinutes(8))
                .build();
        //生成代理类对象
        Assistant assistant = AiServices.builder(Assistant.class)
                .chatModel(model)
                .chatMemoryProvider(chatMemoryProvider) //存储
                .tools(new MyTools())
                .build();
//        String a= assistant.chat(5,"小明问妈妈，1到100的和是多少？");
//        System.out.println(a);
//        System.out.println("-----------------");
        String b = assistant.chat(5, "我想知道衡阳现在的天气是多少，单位是摄氏度");
        System.out.println(b);
        System.out.println("-----------------");

    }
}
